package com.example.myapplication.network;

import android.text.TextUtils;

import androidx.annotation.NonNull;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

/**
 * 请求接口算法加密
 */
public class MD5 {

    public static HashMap<String, Object> setSign(HashMap<String, Object> paramMap) {
        long timestamp = System.currentTimeMillis();
        paramMap.put("wlc_time", timestamp);//限制失效时间
        StringBuffer sb = new StringBuffer();
        for (String key : paramMap.keySet()) {
            sb.append(key + "=" + paramMap.get(key).toString() + "&");
        }
        sb.append("wlc_Key=wlcxxxxxxclw");//验证秘钥
        paramMap.put("wlc_sign", MD5.md5(sb.toString()).toUpperCase());//签名验证
        return paramMap;
    }

    @NonNull
    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}
